package com.swt.testdemo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swt.testdemo.config.ResponseBean;
import com.swt.testdemo.config.ResponseMessage;
import com.swt.testdemo.dao.SysMsgDao;
import com.swt.testdemo.dao.SysMsgNoticeDao;
import com.swt.testdemo.dao.SysUserDao;
import com.swt.testdemo.entity.SysMsgEntity;
import com.swt.testdemo.entity.SysMsgNoticeEntity;
import com.swt.testdemo.exception.AgyException;
import com.swt.testdemo.form.CreateMsgForm;
import com.swt.testdemo.form.EditMsgForm;
import com.swt.testdemo.form.QueryMsgForm;
import com.swt.testdemo.service.SysMsgNoticeService;
import com.swt.testdemo.service.SysMsgService;
import com.swt.testdemo.util.RedisUtil;
import com.swt.testdemo.util.ValidatorUtil;
import com.swt.testdemo.vo.SysMsgNoticeInfoVO;
import com.swt.testdemo.vo.SysUserMapVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author BleethNie
 * @version 1.0
 * @date 2020/11/11 17:09
 **/
@Service("SysMsgService")
public class SysMsgServiceImpl extends ServiceImpl<SysMsgDao, SysMsgEntity> implements SysMsgService {

    @Autowired
    private SysMsgDao sysMsgDao;

    @Autowired
    private SysMsgNoticeDao sysMsgNoticeDao;
    
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysMsgNoticeService sysMsgNoticeService;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public ResponseBean listMsg(QueryMsgForm form) {
        //参数校验
        ValidatorUtil.validateEntity(form);


        String msgContentFilter = form.getMsgContentFilter();
        String msgLevelFilter = form.getMsgLevelFilter();
        String msgTypeFilter = form.getMsgTypeFilter();
        Page<SysMsgEntity> entityPage = new Page<>(form.getPage(), form.getLimit());
        IPage<SysMsgEntity> resultPage = sysMsgDao.listMsg(entityPage, msgContentFilter, msgLevelFilter, msgTypeFilter);
        return new ResponseBean(200,"查询成功",resultPage);

    }

    @Override
    public ResponseBean getMsgInfo(Integer msgId) {
        String key = "msg:info:"+msgId;
        SysMsgNoticeInfoVO sysMsgNoticeInfoVO = redisUtil.getObject(key, SysMsgNoticeInfoVO.class);
        if (sysMsgNoticeInfoVO == null){
            SysMsgEntity sysMsgEntity = this.getById(msgId);
            String status = sysMsgEntity.getStatus();
            if (sysMsgEntity == null || StrUtil.isEmpty(status) || status.equals(SysMsgEntity.STATUS_DELETE)){
                throw new AgyException("当前消息不存在，请检查后重试....");
            }
            List<SysMsgNoticeEntity> msgNoticeEntityList = sysMsgNoticeDao.getByMsgId(msgId);
            sysMsgNoticeInfoVO = new SysMsgNoticeInfoVO();

            BeanUtils.copyProperties(sysMsgEntity,sysMsgNoticeInfoVO);

            List<SysMsgNoticeInfoVO.SysMsgNoticeVo> noticeList = new ArrayList<>();

            if (msgNoticeEntityList !=null && !msgNoticeEntityList.isEmpty()){
                   noticeList= msgNoticeEntityList.stream().map(entity->{
                       SysMsgNoticeInfoVO.SysMsgNoticeVo sysMsgNoticeVo = new SysMsgNoticeInfoVO.SysMsgNoticeVo();
                       BeanUtils.copyProperties(entity,sysMsgNoticeVo);
                       return sysMsgNoticeVo;
                   }).collect(Collectors.toList());
            }
            sysMsgNoticeInfoVO.setNoticeList(noticeList);
            redisUtil.setObject(key,sysMsgNoticeInfoVO,RedisUtil.ONE_HOUR_EXPIRE_TIME);

        }
        return new ResponseBean(200,"查询成功",sysMsgNoticeInfoVO);
    }

    @Override
    public ResponseBean createMsg(CreateMsgForm form) {
        //参数校验
        ValidatorUtil.validateEntity(form);


        SysMsgEntity sysMsgEntity =new SysMsgEntity();
        BeanUtils.copyProperties(form,sysMsgEntity);

        DateTime current = DateUtil.date();
        DateTime expireTime = DateUtil.offsetMonth(current, 3);
        sysMsgEntity.setCreatedTime(current);
        sysMsgEntity.setUpdateTime(current);
        sysMsgEntity.setExpireTime(expireTime);

        sysMsgEntity.setMsgType(SysMsgEntity.MSG_TYPE_ADMIN);
        sysMsgEntity.setStatus(SysMsgEntity.STATUS_OK);

        boolean success = this.save(sysMsgEntity);
        Integer msgId = sysMsgEntity.getId();
        if (success){
            List<Integer> userList = new ArrayList<>();
            if (sysMsgEntity.getSendType().equals(SysMsgEntity.SEND_TYPE_GLOBAL)){
                List<SysUserMapVO> sysUserMapVOS = sysUserDao.queryUserAsMap(null, null);
                        userList=sysUserMapVOS.stream().map(vo->{
                            Integer userId = vo.getUserId();

                            return userId;
                        }).collect(Collectors.toList());
            }else {
                userList = form.getUserList();
            }
            List<SysMsgNoticeEntity> sysMsgNoticeEntityList = userList.stream().map(userId -> {
                 SysMsgNoticeEntity sysMsgNoticeEntity = new SysMsgNoticeEntity();
                 sysMsgNoticeEntity.setMsgId(msgId);
                 sysMsgNoticeEntity.setUserId(userId);
                 sysMsgNoticeEntity.setReadStatus(SysMsgNoticeEntity.READ_STATUS_UNREAD);
                 return sysMsgNoticeEntity;
            }).collect(Collectors.toList());
            sysMsgNoticeService.saveBatch(sysMsgNoticeEntityList);
        }

        return new ResponseBean(200,"创建成功",sysMsgEntity);
    }

    @Override
    public ResponseMessage editMsg(EditMsgForm form) {
        String key = "msg:info:"+form.getId();
        redisUtil.del(key);


        //参数检验
        ValidatorUtil.validateEntity(form);
        Integer msgId = form.getId();

        SysMsgEntity sysMsgEntity = new SysMsgEntity();

        BeanUtils.copyProperties(form,sysMsgEntity);
        DateTime current = DateUtil.date();
        sysMsgEntity.setUpdateTime(current);

        this.updateById(sysMsgEntity);

        List<Integer>  userList = new ArrayList<>();
        if (form.getSendType().equals(SysMsgEntity.SEND_TYPE_PART)){
            userList = form.getUserList();
        }else {
            List<SysUserMapVO> sysUserMapVOS = sysUserDao.queryUserAsMap(null, null);
            userList = sysUserMapVOS.stream().map(vo -> {
                Integer userId = vo.getUserId();
                return userId;
            }).collect(Collectors.toList());

        }
         //删除阅读情况
        QueryWrapper<SysMsgNoticeEntity> wq = new QueryWrapper<>();
        wq.eq("msg_id",msgId);
        sysMsgNoticeService.remove(wq);

         //新增userId中存在，但是数据库中不存在的用户
        List<SysMsgNoticeEntity> sysMsgNoticeEntityList = userList.stream().map(userId -> {
            SysMsgNoticeEntity sysMsgNoticeEntity = new SysMsgNoticeEntity();
            sysMsgNoticeEntity.setUserId(userId);
            sysMsgNoticeEntity.setMsgId(form.getId());
            sysMsgNoticeEntity.setReadStatus(SysMsgNoticeEntity.READ_STATUS_UNREAD);
            return sysMsgNoticeEntity;
        }).collect(Collectors.toList());
         sysMsgNoticeService.saveBatch(sysMsgNoticeEntityList);

        return new ResponseMessage(200,"修改成功");
    }

    @Override
    public ResponseMessage delMsg(Integer msgId) {
        String key ="msg:info:"+msgId;
        redisUtil.del(key);

        SysMsgEntity sysMsgEntity = this.getById(msgId);
        if (sysMsgEntity == null){
            throw new AgyException("你所要删除的消息不存在，请检查后重试....");
        }
        sysMsgEntity = new SysMsgEntity();
        sysMsgEntity.setId(msgId);
        sysMsgEntity.setStatus(SysMsgEntity.STATUS_DELETE);
        this.updateById(sysMsgEntity);
        return new ResponseMessage(200,"删除成功");
    }
}
